from functools import wraps
import flask
import json
import const
import MySQL
import tools
server = flask.Flask("abc")
def check_token(func):#装饰器，函数运行前校验token
    @wraps(func)
    def inner(*args,**kwargs):
        print("check_token装饰器")
        token = flask.request.values.get("token")
        user_id = tools.check_token(token)
        if not user_id:
            return json.dumps({"code": -2, "msg": "未登录"}, ensure_ascii=False)
        ret=func(*args,**kwargs)
        return ret
    return inner
def check_money(func):#装饰器
    @wraps(func)
    def inner(*args,**kwargs):
        print("check_money装饰器")
        money = flask.request.values.get("money")
        money = tools.check_money(money)
        if not money:
            return json.dumps({"code": -3, "msg": "金额错误！"}, ensure_ascii=False)
        ret=func(*args,**kwargs)
        return ret
    return inner
@server.route('/user/login', methods=['post'])
def login():
    # 必填参数：username,password
    username = flask.request.values.get("username")
    password = tools.md5(flask.request.values.get("password"))
    sql = 'select * from fmz_user where (email="%s" or phone="%s") and password="%s";' % (username,username,password)
    m = MySQL.MySQL(const.mysql_info,2)
    result = m.fetchone(sql)
    if not result:
        return json.dumps({"code":-1,"msg":"账号/密码不正确"}, ensure_ascii=False)
    token = tools.create_token(username)
    r = tools.create_redis()
    #token:xxxx
    r.set("token:%s"%token,result.get("id"),const.token_expire)
    return json.dumps({"code":0,"msg":"登录成功","token":token}, ensure_ascii=False)

@server.route('/pay', methods=['post'])
@check_token
@check_money
def pay():
    money = int(flask.request.values.get("money"))#装饰器校验money通过，money应该是应int类型
    token = flask.request.values.get("token")
    user_id = tools.check_token(token)
    #写入装饰器@check_token
    # if not user_id:
    #     return json.dumps({"code": -2, "msg": "未登录"}, ensure_ascii=False)

    #写入装饰器@check_money
    # money = tools.check_money(money)
    # if not money:
    #     return json.dumps({"code": -3, "msg": "金额错误！"}, ensure_ascii=False)

    sql = "select * from fmz_account where user_id = %s ;" %  user_id
    m = MySQL.MySQL(const.mysql_info,2)
    result = m.fetchone(sql)
    balance = result.get("money")
    if money > balance:
        return json.dumps({"code": -4, "msg": "余额不足！"}, ensure_ascii=False)
    #数据库本身的money-接口传过来的money
    update_sql = "update fmz_account set money=money-%s where user_id= %s" % (money,user_id)
    m.execute(update_sql)

    return json.dumps({"code": 0, "msg": "支付成功！","balance":balance - money}, ensure_ascii=False)


@server.route('/recharge',methods=['post'])
@check_token
@check_money
# #报错：AssertionError: View function mapping is overwriting an existing endpoint function: inner
# # 被装饰器装饰的名字变了，之前是pay，现在是recharge，装饰器里面的名字都是inner,在inner方法名上加装饰器@wraps(func)，修改inner为随机的函数名
def recharge():
    money = int(flask.request.values.get("money"))
    token = flask.request.values.get("token")
    user_id = tools.check_token(token)
    update_sql = "update fmz_account set money=money+%s where user_id= %s" % (money,user_id)
    m = MySQL.MySQL(const.mysql_info)
    m.execute(update_sql)
    query_sql = "select money from fmz_account where user_id = %s " % user_id
    balance = m.fetchone(query_sql)[0]
    return json.dumps({"code": 0, "msg": "充值成功！","balance":balance}, ensure_ascii=False)



server.run(debug=True, port=8888, host='0.0.0.0')

